package com.showcase.cloud.gateway.feign.config;

import com.showcase.cloud.gateway.utils.TokenContexHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;

/**
 * 拦截请求，给requestTemplate 增加header
 */
@Configuration
public class FeignTokenRequestInterceptor implements RequestInterceptor {
    @Value("${jwt.header}")
    private String tokenHeader;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes != null){
            HttpServletRequest request = attributes.getRequest();
            requestTemplate.header(tokenHeader, request.getHeader(tokenHeader));
        }
        if(StringUtils.isNotEmpty(TokenContexHolder.get())){
            requestTemplate.header(tokenHeader, TokenContexHolder.get());
        }
    }

}
